package com.github.niefy.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

/**
 * @author : [86188]
 * @description : [用于封装http请求]
 * @createTime : [2022/9/27 9:51]
 * @updateUser : [86188]
 * @updateTime : [2022/9/27 9:51]
 */
@Slf4j
public class HttpClientUtil {
    /**
     * 使用jdk11原生方式发送post请求
     * @param targetUri
     * @param obj
     * @param clazz
     * @param <T>
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    public static <T> T http2PostJsonSync(String targetUri, Object obj, Class<T> clazz) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(targetUri))
                .timeout(Duration.ofMinutes(1))
                .header(Header.CONTENT_TYPE.getValue(), "application/json;charset=utf-8")
                .POST(HttpRequest.BodyPublishers.ofString(JSONUtil.toJsonStr(obj)))
                .build();
        HttpResponse.BodyHandler<String> responseBodyHandler = HttpResponse.BodyHandlers.ofString();
        HttpResponse<String> response = client.send(request, responseBodyHandler);
        String body = response.body();
        var bean = JSONUtil.toBean(body, clazz);
        //TODO 在这里对其他系统返回的内容使用javax.validtion进行有效性校验
        return bean;
    }

    /**
     * 发送get请求
     * @param targetUri api调用目标地址
     * @param outParam 输出对象
     * @param responseType 接口返回信息映射接收对象的类型
     * @return <T>类型的对象
     */
    public static <T> T http2GetJsonSync(String targetUri, Class<T> responseType, Object outParam) {
        log.debug(HttpUtil.urlWithForm(targetUri, BeanUtil.beanToMap(outParam,true,true), StandardCharsets.UTF_8, false));
        String body = HttpUtil.get(targetUri, BeanUtil.beanToMap(outParam,true,true));
        log.debug(body);
        var responseObj = JSONUtil.toBean(body, responseType);
        //TODO 可以在这里对其他系统返回的内容使用javax.validtion进行有效性校验
        /*ValidatorUtils.validateEntity();*/
        return responseObj;
    }

    public static String http2GetStringSync(String targetUri, Object outParam) {
        log.debug(HttpUtil.urlWithForm(targetUri, BeanUtil.beanToMap(outParam), StandardCharsets.UTF_8, false));
        String body = HttpUtil.get(targetUri, BeanUtil.beanToMap(outParam));
        return body;
    }
}
